# -*- coding: utf-8 -*-
# @Time : 2022/3/21 9:29
# @FileName: Config.py
# @Mail: lizhigen1996@aliyun.com

__author__ = 'Zhigen.li'

import os
import json
from datetime import datetime
from functools import wraps
from PyQt5.QtWidgets import QMessageBox
from Tools.DBTool import DBSession

KTopLayout = 'TopLayout'
KFixed = 'Fixed'
KClock = 'Clock'
KFund = 'Fund'
KRemberPW = 'RemberPW'
KAutoLogin = 'AutoLogin'
KUserRole = 'UserRole'
KUserName = 'UserName'
KUserPW = 'UserPW'
KAccountBook = 'AccountBook'

Version = '202205231400'

def CatchExceptions(a_func):
    @wraps(a_func)
    def wrapTheFunction(*args):
        try:
            res = a_func(*args)
            return res
        except Exception as e:
            try:
                # 将错误信息写入db
                db = DBSession()
                err = str(a_func) + ": " + str(e)
                if len(err) > 2048:
                    err = err[:2048]
                try:
                    name = config.dbName
                except:
                    name = 'NA'
                db.setErrorMsg(name, err)
                del db
                if len(args) > 0 and 'class' in str(type(args[0])):
                    QMessageBox.warning(args[0], '错误提示', str(e))
                print('CatchExceptions: {}'.format(str(e)))
            except Exception as e:
                print(e)
            return None
    return wrapTheFunction

class Config(object):
    def __init__(self):
        self.path = 'C:\\Config\\config.json'
        if not os.path.exists(r'C:\Config'):
            os.makedirs(r'C:\Config')

        if not os.path.exists(self.path):
            self.configDic = {KTopLayout: False, KFixed: False, KRemberPW: True, KAutoLogin: False, KUserRole: False, KClock: '9:30,14:30,14:50', KFund: []}
            with open(self.path, 'w')as fp:
                fp.write(json.dumps(self.configDic, indent=4))
        else:
            try:
                with open(self.path, 'r')as fp:
                    data = fp.read()
                    self.configDic = json.loads(data)
            except:
                self.configDic = {KTopLayout: False, KFixed: False, KRemberPW: True, KAutoLogin: False,
                                  KUserRole: False, KClock: '9:30,14:30,14:50', KFund: []}
                with open(self.path, 'w')as fp:
                    fp.write(json.dumps(self.configDic, indent=4))

        self.settings = {}
        print(self.configDic)

    def getTopLayout(self):
        return self.configDic.get(KTopLayout, False)

    def setTopLayout(self, b: bool):
        self.configDic[KTopLayout] = b
        with open(self.path, 'w')as fp:
            fp.write(json.dumps(self.configDic, indent=4))

    def getFixed(self):
        return self.configDic.get(KFixed, False)

    def setFixed(self, b: bool):
        self.configDic[KFixed] = b
        with open(self.path, 'w')as fp:
            fp.write(json.dumps(self.configDic, indent=4))

    def getFund(self):
        return self.configDic.get(KFund, [])

    def addFund(self, data: dict):
        funds = self.configDic.get(KFund, [])
        for f in funds:
            if f['fundcode'] == data['fundcode']:
                return False
        funds.append({'fundcode': data['fundcode'], 'name': data['name']})
        self.configDic[KFund] = funds
        with open(self.path, 'w')as fp:
            fp.write(json.dumps(self.configDic, indent=4))
        return True

    def delFund(self, fundCode):
        funds = self.configDic.get(KFund, [])
        for idx, f in enumerate(funds):
            if f['fundcode'] == fundCode:
                funds.remove(f)
                break
        self.configDic[KFund] = funds
        with open(self.path, 'w')as fp:
            fp.write(json.dumps(self.configDic, indent=4))

    def getRemberPW(self):
        return self.configDic.get(KRemberPW, True)

    def setRemberPW(self, b: bool):
        self.configDic[KRemberPW] = b
        with open(self.path, 'w')as fp:
            fp.write(json.dumps(self.configDic, indent=4))

    def getAutoLogin(self):
        return self.configDic.get(KAutoLogin, False)

    def setAutoLogin(self, b: bool):
        self.configDic[KAutoLogin] = b
        with open(self.path, 'w')as fp:
            fp.write(json.dumps(self.configDic, indent=4))

    def getUserRole(self):
        return self.configDic.get(KUserRole, False)

    def setUserRole(self, b: bool):
        self.configDic[KUserRole] = b
        with open(self.path, 'w')as fp:
            fp.write(json.dumps(self.configDic, indent=4))

    def getUserInfo(self):
        return self.configDic.get(KUserName, ''), self.configDic.get(KUserPW, '')

    def setUserInfo(self, name, pw):
        self.configDic[KUserName] = name
        self.configDic[KUserPW] = pw
        with open(self.path, 'w')as fp:
            fp.write(json.dumps(self.configDic, indent=4))

    def getClock(self):
        return self.configDic.get(KClock, '')

    def setClock(self, text: str):
        text = text.replace('：', ':')
        text = text.replace('，', ',')
        self.configDic[KClock] = text
        with open(self.path, 'w')as fp:
            fp.write(json.dumps(self.configDic, indent=4))

    def getAccountBook(self):
        return self.configDic.get(KAccountBook, {})

    def addAccountBook(self, fundCode, buyInfo, shareWay):
        accountBook = self.getAccountBook()
        if fundCode in accountBook.keys():
            accountBook[fundCode]['BuyInfos'].append(buyInfo)
        else:
            accountBook[fundCode] = {'BuyInfos': [buyInfo, ], 'ShareWay': shareWay}
        self.configDic[KAccountBook] = accountBook
        with open(self.path, 'w')as fp:
            fp.write(json.dumps(self.configDic, indent=4))

    def delAccountBook(self, fundCode):
        accountBook = self.getAccountBook()
        if not fundCode in accountBook.keys():
            return
        del accountBook[fundCode]
        self.configDic[KAccountBook] = accountBook
        with open(self.path, 'w')as fp:
            fp.write(json.dumps(self.configDic, indent=4))


    def clear(self):
        self.configDic = {KTopLayout: False, KFixed: False, KRemberPW: True, KAutoLogin: False, KUserRole: False,
                          KClock: '9:30,14:30,14:50', KFund: []}
        with open(self.path, 'w')as fp:
            fp.write(json.dumps(self.configDic, indent=4))

    def getDBInfo(self, name, pw):
        db = DBSession()
        self.dbName, self.dbPw, self.dbRc, self.dbFc, self.dbIp, self.dbAl = db.checkUserInfo(name, pw)
        self.checkRobot = db.checkRobotCode()
        self.settings = db.getSetting()
        del db
        return self.dbName, self.dbPw, self.dbRc, self.dbFc, self.dbIp, self.dbAl, self.checkRobot

    def loginWithNoUI(self):
        db = DBSession()
        self.dbName, self.dbPw, self.dbRc, self.dbFc, self.dbIp, self.dbAl = db.loginWithNoUI()
        self.checkRobot = db.checkRobotCode()
        del db
        return self.dbName, self.dbPw, self.dbRc, self.dbFc, self.dbIp, self.dbAl, self.checkRobot

    def getSetting(self):
        db = DBSession()
        self.settings = db.getSetting()
        del db

    def checkNewVersion(self):
        try:
            db = DBSession()
            version, url, forcedUpdating = db.getNewVersion()
            if version and url:
                nowV = datetime.strptime(Version, '%Y%m%d%H%M')
                checkV = datetime.strptime(version, '%Y%m%d%H%M')
                if checkV > nowV:
                    del db
                    return True, url, forcedUpdating
        except:
            pass
        return False, None, None

    def setSuggest(self, text):
        db = DBSession()
        db.setSuggest(self.dbName, text)
        del db

    def getMaxFundsCount(self):
        try:
            return self.dbFc
        except:
            return 0

    def getVersion(self):
        return Version


config = Config()
